/**
 * Created by Winter on 2016/4/30.
 */
function showError(input,error){
    $("div[id^='error_']").hide();
    $("#error_"+input+" div:first-child").html(error);
    $("#error_"+input).show();
    $("#input_"+input)[0].focus();
}

function showLoadingDialog(msg){
    $("div[id^='error_']").hide();
    $("#loading_dialog .weui_toast_content").html(msg);
    $("#loading_dialog").show();
}

// 验证车牌号
function validatePlateNo (obj) {
    var reg = /^[0-9a-zA-Z]{5}$/;
    return !(obj.length == 0 || !obj.match(reg));
}

// 验证车架号
function validateBodyNo (obj) {
    var reg = /^[0-9a-zA-Z]{4}$/;
    return !(obj.length == 0 || !obj.match(reg));
}

function hideLoadingDialog(){
    $("#loading_dialog").hide();
}

function showAlertDialog(msg){
    $("#alert_dialog .weui_dialog_bd").html(msg);
    $("#alert_dialog").show();
    $("#alert_dialog .primary").click(function(){
        $("#alert_dialog").hide();
    });
}

$(function() {
    $("#btn_bodyno_tips").click(function () {
        $("#bodyno_tips_layout").toggle("fast");
    });
    $("#btn_password_tips").click(function () {
        $("#password_tips_layout").toggle("fast");
    });
    $("#btn_query").click(function(){
        //验证车牌号码
        var carNo = $("#input_car").val().trim();
        if (carNo.length == 0){
            showError("card", "车牌号码不能为空");
            return;
        } else if (!validatePlateNo(carNo)) {
            showError("card", "请输入正确的车牌号码");
            return;
        } else {
            carNo =  $("#car_province").val().trim() + $("#car_preid").val().trim() + carNo;
        }
        //验证车身架号
        var bodyNo = $("#input_bodyno").val().trim();
        if (bodyNo.length == 0){
            showError("bodyno", "车身架号不能为空");
            return;
        } else if (!validateBodyNo(bodyNo)) {
            showError("bodyno", "请输入正确的车身架号");
            return;
        }
        addHistory(carNo, bodyNo);
        showLoadingDialog('查询中');
        $.ajax({
            type:'get',
            url:'/query/get-query-details',
            cache:false,
            dataType:'json',
            data:{
                carNo:carNo,
                bodyNo:bodyNo
            },
            success:function(data){
                var code = data['code'];
                hideLoadingDialog();
                if(code == 0){
                    window.location = "/query/index";
                }else{
                    var error = data['error'];

                    if(code == 1){
                        showError("card", error);
                    }else if(code == 2){
                        showError("password", error);
                    }else if(code == 3){
                        showAlertDialog(error);
                    }
                }
            },
            error:function(){
                hideLoadingDialog();
                showHistoryItems();
                showAlertDialog("系统异常，请稍候重试");
            }
        });
    });
});

var viewHistory;
function showHistoryItems() {
    //初始化
    viewHistory = new TrafficeHistory();
    viewHistory.init({
        limit: 6,
        storageKey: 'TrafficeHistory',
        primaryKey: 'chepai'
    });
    //循环显示localStorage里的键值对
    var cell = "";

    // 获取浏览记录
    var histories = viewHistory.getHistories();
    for (var i = histories.length - 1; i >= 0; i--){
        if (!$("#history_area").isShown) {
            $("#history_area").show();
        }
        if (i == histories.length - 1) {
            cell = cell + "<div class='weui_grids'>";
        }
        var history = histories[i];
        cell = cell + "<div class='weui_grid' chepai='" + history.chepai + "' chejia='" + history.chejia + "' ><div class='weui_grid_label'> <label class='weui_label'>"
            + history.chepai + "</label></div><div class='closeLayer' style='display: none'>"
            + "<img src='" + INDEX_URL + "../images/close.png' style='width: 18px; height:18px;'></div></div>";

    }
    if (cell != "") {
        cell = cell + "</div>";
    }

    $("#history_area").append(cell);
    var editFlag = false;
    $('.weui_grid').click(function(){
        if (editFlag) {
            showConfirmDialog($(this))
        } else {
            var chejiahao = $(this).attr('chejia');
            $("#input_bodyno").text = chejiahao;
            var chepaihao = $(this).attr('chepai');
            var strSheng = chepaihao.substring(0, 1);
            var strHaoduan = chepaihao.substring(1,2);
            var strHao = chepaihao.substring(2);
            $("#car_province").val(strSheng);
            $("#car_preid").val(strHaoduan);
            $("#input_car").val(strHao);
            $("#input_bodyno").val(chejiahao);
        }
    }).longpress(function(){
        if (!editFlag) {
            editFlag = true;
            $(".closeLayer").show();
        }
    });
}
showHistoryItems();

function addHistory(carNo, bodyNo) {

    //保存页面信息 如果 ViewHistory 的实例存在，则可以将页面信息写入。
    if (viewHistory) {
        var page = {
            "chejia": bodyNo,
            "chepai": carNo // 这是 primaryKey
        };
        viewHistory.addHistory(page);
    }
}
var elForDeleted;
function showConfirmDialog(el) {
    elForDeleted = el;
    if (!$(".weui_dialog_confirm").isShown) {
        $(".weui_dialog_confirm").show();
    }

}

function hideConfirmDialog() {
    elForDeleted = null;
    $(".weui_dialog_confirm").hide();

}

function deleteHistory() {
    if(elForDeleted) {
        var chepaihao = elForDeleted.attr('chepai');
        var chejiahao = elForDeleted.attr('chejia');
        var item = {
            "chejia": chejiahao,
            "chepai": chepaihao // 这是 primaryKey
        };
        if (viewHistory) {
            viewHistory.removeHistory(item);
        }
        $(".weui_grids").remove();
        hideConfirmDialog();
        showHistoryItems();
    }

}